<template>
  <q-dialog v-model="show" @hide="handleClose">
    <q-card class="group-call-member-dialog">
      <q-card-section class="dialog-header">
        <div class="dialog-title">选择通话成员</div>
        <div class="dialog-subtitle">选择要发起语音或视频通话的群成员</div>
        <q-btn 
          icon="close" 
          flat 
          round 
          dense 
          class="close-btn"
          @click="handleClose"
        />
      </q-card-section>

      <q-card-section class="dialog-body">
        <q-input
          v-model="searchQuery"
          placeholder="搜索成员"
          outlined
          dense
          class="search-input"
          autocomplete="off"
          clearable
        >
          <template v-slot:prepend>
            <q-icon name="search" size="18px" />
          </template>
        </q-input>

        <div v-if="filteredMembers.length === 0" class="empty-state">
          <q-icon name="people_outline" size="48px" color="grey-4" />
          <div class="empty-text">
            {{ members.length === 0 ? '暂无成员' : '未找到匹配的成员' }}
          </div>
        </div>

        <div v-else class="members-list">
          <div
            v-for="member in filteredMembers"
            :key="member.member_id"
            class="member-item"
            :class="{ selected: selectedMemberIds.includes(member.member_id) }"
            @click="toggleMember(member.member_id, $event)"
          >
            <q-checkbox
              v-model="selectedMemberIds"
              :val="member.member_id"
              class="member-checkbox"
              @click.stop
            />
            <q-avatar size="40px" class="member-avatar">
              <img 
                v-if="member.avatar" 
                :src="member.avatar" 
                @error="handleAvatarError($event, member)"
              />
              <div
                v-else
                class="avatar-placeholder"
                :style="getAvatarStyle(member.member_id)"
              >
                {{ member.displayName?.[0]?.toUpperCase() || 'U' }}
              </div>
            </q-avatar>
            <div class="member-info">
              <div class="member-name">{{ member.displayName }}</div>
              <div v-if="member.alias && member.alias !== member.displayName" class="member-alias">
                {{ member.alias }}
              </div>
            </div>
            <div v-if="member.role === 2" class="member-role">
              <q-chip size="sm" color="primary" text-color="white">群主</q-chip>
            </div>
            <div v-else-if="member.role === 1" class="member-role">
              <q-chip size="sm" color="secondary" text-color="white">管理员</q-chip>
            </div>
          </div>
        </div>
      </q-card-section>

      <q-card-actions align="right" class="dialog-actions">
        <q-btn
          flat
          label="取消"
          color="grey-7"
          @click="handleClose"
          class="cancel-btn"
        />
        <q-btn
          flat
          label="语音通话"
          color="primary"
          icon="phone"
          :disable="selectedMemberIds.length === 0"
          @click="handleVoiceCall"
          class="action-btn"
        />
        <q-btn
          flat
          label="视频通话"
          color="primary"
          icon="videocam"
          :disable="selectedMemberIds.length === 0"
          @click="handleVideoCall"
          class="action-btn"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { getAvatarStyle } from '@/utils/avatar'
import { API_BASE_URL } from '@/config/env'

export interface GroupMember {
  member_id: string
  displayName: string
  alias?: string
  avatar?: string
  role?: number
}

const props = defineProps<{
  modelValue: boolean
  members: GroupMember[]
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'voice-call': [memberIds: string[]]
  'video-call': [memberIds: string[]]
}>()

const show = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const searchQuery = ref('')
const selectedMemberIds = ref<string[]>([])

const filteredMembers = computed(() => {
  if (!searchQuery.value.trim()) {
    return props.members
  }
  const query = searchQuery.value.toLowerCase().trim()
  return props.members.filter(m => 
    m.displayName.toLowerCase().includes(query) ||
    (m.alias && m.alias.toLowerCase().includes(query)) ||
    m.member_id.toLowerCase().includes(query)
  )
})

const toggleMember = (memberId: string, event?: Event) => {
  // 如果点击的是 checkbox，跳过（checkbox 会自己处理）
  if (event && (event.target as HTMLElement).closest('.member-checkbox')) {
    return
  }
  const index = selectedMemberIds.value.indexOf(memberId)
  if (index > -1) {
    selectedMemberIds.value.splice(index, 1)
  } else {
    selectedMemberIds.value.push(memberId)
  }
}

const handleVoiceCall = () => {
  if (selectedMemberIds.value.length > 0) {
    emit('voice-call', [...selectedMemberIds.value])
    handleClose()
  }
}

const handleVideoCall = () => {
  if (selectedMemberIds.value.length > 0) {
    emit('video-call', [...selectedMemberIds.value])
    handleClose()
  }
}

const handleClose = () => {
  show.value = false
  searchQuery.value = ''
  selectedMemberIds.value = []
}

const handleAvatarError = (event: Event, member: GroupMember) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

watch(() => props.modelValue, (val) => {
  if (val) {
    selectedMemberIds.value = []
    searchQuery.value = ''
  }
})
</script>

<style lang="sass" scoped>
.group-call-member-dialog
  min-width: 420px
  max-width: 500px
  border-radius: 12px
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale

.dialog-header
  padding: 24px 24px 16px
  position: relative
  border-bottom: 1px solid rgba(0, 0, 0, 0.06)

  .dialog-title
    font-size: 18px
    font-weight: 600
    letter-spacing: -0.01em
    color: #1a1a1a
    line-height: 1.4
    margin-bottom: 4px

  .dialog-subtitle
    font-size: 13px
    font-weight: 400
    letter-spacing: 0.01em
    color: #718096
    line-height: 1.5

  .close-btn
    position: absolute
    top: 20px
    right: 16px
    color: #718096

    &:hover
      background: rgba(0, 0, 0, 0.04)

.dialog-body
  padding: 16px 24px
  max-height: 400px
  overflow-y: auto

  .search-input
    margin-bottom: 16px

    :deep(.q-field__control)
      height: 40px

    :deep(.q-field__native)
      font-size: 14px
      letter-spacing: 0.01em
      color: #1a1a1a

    :deep(.q-field__label)
      font-size: 14px
      color: #718096

  .empty-state
    display: flex
    flex-direction: column
    align-items: center
    justify-content: center
    padding: 48px 24px
    color: #a0aec0

    .empty-text
      margin-top: 12px
      font-size: 14px
      font-weight: 400
      letter-spacing: 0.01em
      color: #718096

  .members-list
    .member-item
      display: flex
      align-items: center
      padding: 12px 0
      cursor: pointer
      border-radius: 8px
      transition: background-color 0.15s ease
      margin-bottom: 4px

      &:hover
        background: rgba(0, 0, 0, 0.02)

      &.selected
        background: rgba(25, 118, 210, 0.08)

      .member-checkbox
        margin-right: 12px

      .member-avatar
        margin-right: 12px
        flex-shrink: 0

        .avatar-placeholder
          width: 100%
          height: 100%
          display: flex
          align-items: center
          justify-content: center
          color: white
          font-size: 16px
          font-weight: 500
          letter-spacing: 0
          -webkit-font-smoothing: antialiased
          -moz-osx-font-smoothing: grayscale

      .member-info
        flex: 1
        min-width: 0

        .member-name
          font-size: 15px
          font-weight: 500
          letter-spacing: 0.01em
          color: #1a1a1a
          line-height: 1.4
          margin-bottom: 2px
          overflow: hidden
          text-overflow: ellipsis
          white-space: nowrap

        .member-alias
          font-size: 13px
          font-weight: 400
          letter-spacing: 0.01em
          color: #718096
          line-height: 1.4
          overflow: hidden
          text-overflow: ellipsis
          white-space: nowrap

      .member-role
        margin-left: 8px
        flex-shrink: 0

.dialog-actions
  padding: 12px 24px 20px
  border-top: 1px solid rgba(0, 0, 0, 0.06)
  display: flex
  justify-content: flex-end
  gap: 8px

  .cancel-btn, .action-btn
    min-width: 100px
    height: 36px
    font-size: 14px
    font-weight: 500
    letter-spacing: 0.02em
    text-transform: none
    border-radius: 6px
    -webkit-font-smoothing: antialiased
    -moz-osx-font-smoothing: grayscale

  .action-btn
    &:disabled
      opacity: 0.4
</style>

